import orjson
from fastapi import APIRouter, Depends, HTTPException, Path
from fastapi.responses import JSONResponse, Response
from config.get_db import get_db_sync as get_db
from sqlalchemy.orm import Session
from yg_crm import schemas, crud, orm
from typing import List, Optional
from utils.utility import result, RespResult, json_result_reps
from sqlalchemy.ext.asyncio import AsyncSession


test_router = APIRouter()



description1 = """
使用自己写的json化函数，
有自动null值处理 
"""
@test_router.get("/test_response_json", description=description1)
async def test():
    user = {"name": "John Doe吴", "email": "john.doe@example.com"}
    json_bytes = orjson.dumps(user)
    return Response(
        content=json_bytes,
        media_type="application/json; charset=UTF-8",
        headers={
            'Accept-Charset': 'utf-8'
        }
    )




# * 处理有默认值，和没默认值情况同时在，函数层的魔术语法。
# 函数参数的规则是：positional param不能在 named param之后；named param只能是其它named param
@test_router.get("/items/{item_id}")
async def read_items(*, item_id: int = Path(title="The ID of the item to get"), q: str):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results


@test_router.get("/tpl_type/create_init_data")
async def set_template_type(db: Session = Depends(get_db)):
    t1 = schemas.TemplateType(code="EC-waybill", name="电商单据样式模板", category='oss', create_by="admin", update_by="admin")
    t2 = schemas.TemplateType(code="Finance-checkbill", name="财务对帐单导出模板", category='json', create_by="admin", update_by="admin")
    res = crud.create_template_type(db, [t1, t2])
    # return result(res, schema=schemas.TemplateType)
    return json_result_reps(data=res)


@test_router.get("/tpl_type/all")
async def set_template_type(db: Session = Depends(get_db)):
    res = crud.get_template_types(db)
    print(res)
    return json_result_reps(data=res)


